package com.jic.order.controller.feign;

import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.order.api.OrderApi;
import com.jic.order.entity.Order;
import com.jic.order.entity.OrderGoods;
import com.jic.order.entity.OrderOutStockNotice;
import com.jic.order.entity.OrderRefund;
import com.jic.order.mapper.OrderGoodsMapper;
import com.jic.order.mapper.OrderMapper;
import com.jic.order.request.CreateParentOrderRequest;
import com.jic.order.request.OrderParentSaleRequest;
import com.jic.order.request.OrderReturnRequest;
import com.jic.order.request.OrderSaleRequest;
import com.jic.order.request.UserQuery;
import com.jic.order.response.FrontOrderStatusCountInfo;
import com.jic.order.response.OrderAllAmountResponse;
import com.jic.order.response.OrderDetailInfo;
import com.jic.order.service.OrderOperateService;
import com.jic.order.service.OrderOutStockNoticeService;
import com.jic.order.service.OrderParentService;
import com.jic.order.service.OrderQueryService;
import com.jic.order.service.OrderRefundService;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.response.ProductAfterInfoByIdResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@Api(tags = {"Feign-依赖接口"})
@RequestMapping(value = "feign")
@RestController

public class OrderFeign implements OrderApi {

	@Autowired
	RedisClientTemplate redisClientTemplate;
	@Autowired
	private OrderOperateService orderOperateService;
	@Autowired
	private OrderQueryService orderQueryService;
	@Autowired
	private OrderParentService orderParentService;
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private OrderGoodsMapper orderGoodsMapper;
	@Resource
	private ProductListApi productListApi;
	@Autowired
	private OrderRefundService orderRefundService;
	@Autowired
	private OrderOutStockNoticeService orderOutStockNoticeService;

	@ApiOperation(value = "创建无货提醒")
	@PostMapping(value = "createOrderOutStockNotice")
	public RestResult<String> createOrderOutStockNotice(@RequestBody OrderOutStockNotice form) {
		long l = orderOutStockNoticeService.insert(form);
		return RestResult.success(1 > 0 ? "成功" : "失败");
	}

	@ApiOperation(value = "创建订单")
	@PostMapping(value = "createOrder")
	public RestResult<String> create(@RequestBody CreateParentOrderRequest createParentOrderRequest) {
		return orderOperateService.createOrder(createParentOrderRequest);
	}

	@ApiOperation(value = "查询用户实付总金额")
	@PostMapping("/queryOrderAllAmountByMember")
	public RestResult<List<OrderAllAmountResponse>> queryOrderAllAmountByMember(@RequestBody List<Long> memberId) {
		try {
			if (memberId.isEmpty()) {
				return RestResult.error("9999", "参数不能为空");
			}
		} catch (Exception e) {
			log.error("error", e);
			return RestResult.error("9999", e.getLocalizedMessage());
		}
		return orderParentService.queryAllAmount(memberId);
	}

	@ApiOperation(value = "查询订单统计数据")
	@PostMapping(value = "queryOrderStatusCount")
	public RestResult<FrontOrderStatusCountInfo> queryOrderStatusCount(@RequestBody UserQuery request) {
		// 获取用户id
		String userStr = redisClientTemplate.get("H5_LOGIN_TOKEN_" + request.getToken());
		if (StringUtils.isEmpty(userStr)) {
			return RestResult.error("4000", "非法请求");
		}
		Map<String, Object> userMap = JSONArray.parseObject(userStr, HashMap.class);
		String userId = userMap.get("id").toString();
		request.setUserId(Long.parseLong(userId));
		return orderQueryService.queryOrderStatusCount(request);
	}

	@ApiOperation(value = "修改订单状态")
	@PostMapping("/updateParentOrderStatus")
	public RestResult<Boolean> updateParentOrderStatus(@RequestParam(value = "orderNo") String orderNo) {
		try {
			if (StringUtils.isEmpty(orderNo)) {
				return RestResult.error("9999", "参数不能为空");
			}
		} catch (Exception e) {
			log.error("error", e);
			return RestResult.error("9999", e.getLocalizedMessage());
		}
		return orderParentService.updateParentOrderStatus(orderNo);
	}

	@Override
	public RestResult<OrderDetailInfo> getOrderInfoByOrderNo(String orderNo) {
		return orderQueryService.getOrderInfoByOrderNo(orderNo);
	}

	@Override
	public List<OrderParentSaleRequest> getOrderInfoByBuyIds(List<Long> distributorIds) {
		List<OrderParentSaleRequest> orderParentSaleRequestList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(distributorIds)) {
			//            distributorIds.forEach(item -> {
			//                //获取所有会员id
			//                List<Long> list = memberUserApi.queryMemberUserListByDistributorIds(item);
			//                if (CollectionUtils.isNotEmpty(list)) {
			//                    list.forEach(item1 -> {
			//                        OrderParent orderParent = new OrderParent();
			//                        orderParent.setBuyerId(item1);
			//                        List<OrderParent> orderParentList = orderParentService.queryOrderInfoByBuyId(orderParent);
			//                        if (CollectionUtils.isNotEmpty(orderParentList)) {
			//                            orderParentList.forEach(item2 -> {
			//                                OrderParentSaleRequest orderParentSaleRequest = new OrderParentSaleRequest();
			//                                //分销员名称
			//                                MememberUserResponse distributorName = memberUserApi.queryMemberUesrById(item);
			//                                if (distributorName != null) {
			//                                    orderParentSaleRequest.setDistributorName(distributorName.getUserAccount());
			//                                    orderParentSaleRequest.setDistributorId(distributorName.getThirdUserId());
			//                                }
			//                                orderParentSaleRequest.setOrderNo(item2.getParentOrderNo());
			//                                orderParentSaleRequest.setBuyId(item1);
			//                                //下单账户
			//                                MememberUserResponse mememberUserResponse = memberUserApi.queryMemberUesrById(item1);
			//                                if (mememberUserResponse != null) {
			//                                    orderParentSaleRequest.setBuyAccount(mememberUserResponse.getUserAccount());
			//                                    orderParentSaleRequest.setBuyName(mememberUserResponse.getNickName());
			//                                }
			//                                orderParentSaleRequest.setOrderStatus(item2.getOrderStatus());
			//                                orderParentSaleRequest.setOrderTime(item2.getBuyerTime());
			//                                orderParentSaleRequest.setOrderTotalAmount(item2.getBuyTotalAmount());
			//                                //支付信息
			//                                OrderPay orderPay = new OrderPay();
			//                                orderPay.setParentOrderNo(item2.getParentOrderNo());
			//                                List<OrderPay> orderPays = orderPayService.query(orderPay);
			//                                if (CollectionUtils.isNotEmpty(orderPays)) {
			//                                    orderParentSaleRequest.setPayStatus(orderPays.get(0).getPayStatus());
			//                                    orderParentSaleRequest.setPayType(orderPays.get(0).getPayType());
			//                                }
			//                                orderParentSaleRequestList.add(orderParentSaleRequest);
			//                            });
			//                        }
			//                    });
			//                }
			//
			//            });
		}
		return orderParentSaleRequestList;
	}

	@Override
	public List<OrderSaleRequest> queryOrderInfoByOrderNo(List<String> orderNo) {
		List<OrderSaleRequest> orderSaleRequestList = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(orderNo)) {
			orderNo.forEach(item -> {
				Order order = new Order();
				order.setParentOrderNo(item);
				List<Order> orderList = orderMapper.query(order);
				if (CollectionUtils.isNotEmpty(orderList)) {
					orderList.forEach(item1 -> {
						OrderGoods orderGoods = new OrderGoods();
						orderGoods.setOrderNo(item1.getOrderNo());
						List<OrderGoods> orderGoodsList = orderGoodsMapper.query(orderGoods);
						if (CollectionUtils.isNotEmpty(orderGoodsList)) {
							orderGoodsList.forEach(item3 -> {
								OrderSaleRequest orderSaleRequest = new OrderSaleRequest();
								orderSaleRequest.setParentOrderNo(item);
								orderSaleRequest.setOrderNo(item1.getOrderNo());
								orderSaleRequest.setOrderStatus(item1.getOrderStatus());
								orderSaleRequest.setProductType(item3.getGoodsType());
								orderSaleRequest.setProductId(item3.getGoodsId());
								orderSaleRequest.setProductName(item3.getGoodsName());
								orderSaleRequest.setProductNum(item3.getGoodsNum());
								orderSaleRequest.setSaleUnitPrice(item3.getSaleUnitPrice());
								orderSaleRequest.setSalePrice(item3.getSaleUnitPrice().multiply(new BigDecimal(item3.getGoodsNum())));
								orderSaleRequest.setBuyTotalAmount(item3.getActualPayTotalAmount());
								orderSaleRequest.setStoreId(item1.getStoreId());
								orderSaleRequest.setStoreName(item1.getStoreName());
								//商品信息
								RestResult<ProductAfterInfoByIdResponse> responseRestResult = productListApi.queryProductInfoById(item3.getGoodsId());
								if (responseRestResult != null && responseRestResult.getData() != null) {
									orderSaleRequest.setProductCode(responseRestResult.getData().getCode());
									orderSaleRequest.setBrandName(responseRestResult.getData().getBrandName());
									orderSaleRequest.setProductUnit(responseRestResult.getData().getUnitName());
									orderSaleRequest.setProductProperty(responseRestResult.getData().getPropertyName());
									orderSaleRequest.setProductCategory(responseRestResult.getData().getFullNamePath());
								}
								orderSaleRequestList.add(orderSaleRequest);
							});
						}
					});
				}
			});
		}
		return orderSaleRequestList;
	}

	@Override
	public List<OrderReturnRequest> queryOrderRefundByOrderNo(String orderNo) {
		List<OrderReturnRequest> orderReturnRequests = new ArrayList<>();
		OrderRefund orderRefund = new OrderRefund();
		orderRefund.setParentOrderNo(orderNo);
		List<OrderRefund> list = orderRefundService.query(orderRefund);
		if (CollectionUtils.isNotEmpty(list)) {
			list.forEach(item -> {
				OrderReturnRequest orderReturnRequest = new OrderReturnRequest();
				orderReturnRequest.setOrderNo(item.getOrderNo());
				orderReturnRequest.setReturnCode(item.getRefundCode());
				orderReturnRequest.setReturnStatus(item.getRefundStatus());
				orderReturnRequest.setReturnAccount(item.getAmount());
				orderReturnRequest.setReturnReason(item.getRefundReason());
				orderReturnRequest.setReturnVoucher(item.getVoucher());
				orderReturnRequest.setPaySerialNo(item.getPaymentNo());
				orderReturnRequests.add(orderReturnRequest);
			});
		}
		return orderReturnRequests;
	}
}
